import React, {Component} from 'react';
import './AuthorityManagementAcount.css';
import $ from 'jquery';
import * as tools from '../../../tools/tools.js';
import WrapAddAcountForm from '../AddAcount/AddAcount';//添加或修改模态框
import WrappedSearchForm from '../../../components/SearchPanel/SearchPanel';
import { DatePicker, message, Form, Row, Col, Input, Button, Icon, Table, Modal, Tooltip, Cascader, Select, Checkbox } from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;




const columns = [
    {
    title: '账号',
    dataIndex: 'count',
  }, {
    title: '角色',
    dataIndex: 'role',
  }, {
    title: '姓名',
    dataIndex: 'name',
  },{
    title: '手机',
    dataIndex: 'phone',
  },{
    title: '所在部门',
    dataIndex: 'department',
  },{
      title : '状态',
      dataIndex: 'status',
  },{
    title : '创建时间',
    dataIndex: 'cTime',
}];

//账号管理主页
class AuthorityManagementAcount extends Component {
    constructor(arg) {
        super(arg);
        this.state = {
            
            //当前选择行 数据对象
            cRow : [],
            visible: false,
            modalTitle : '',
            isModify : 0,
            cTabContent : [],
            cRoles : [],
            paginationC : {},
            cRowKey : [],
            backShowInfo : {},
            searchKeys : [
                {
                    id : 'username',
                    name : '账号',
                    type : 1,
                },
                {
                    id : 'role_id',
                    name : '角色',
                    type : 2,
                    options : [
                        {
                            val : 1,
                            text : '启用'
                        },{
                            val : -1,
                            text : '禁用'
                        }
                    ]
                },
                {
                    id : 'name',
                    name : '姓名',
                    type : 1,//input select
                },
                {
                    id : 'mobile',
                    name : '手机',
                    type : 1,//input date
                },
                {
                    id : 'department',
                    name : '所在部门',
                    type : 1,//input date
                },
                {
                    id : 'status',
                    name : '状态',
                    type : 2,//input date
                    options : [
                        {
                            val : 1,
                            text : '启用'
                        },{
                            val : -1,
                            text : '禁用'
                        }
                    ]
                },
                {
                    id : 'time',
                    name : '创建时间',
                    type : 3
                }
            ]
        }
    }
    handleOk = (e) => {
        this.setState({
            visible: true,
        });
    }

    handleCancel = (e) => {
        this.setState({
            visible: false,
        });
    }
    showModal = (e) => {
        e.target.id == 'add_count';
        //判断当前弹窗状态
        if(e.target.id == 'add_count') {
            console.log('??????')
            this.setState({
                modalTitle : '添加账户',
                isModify : 0,
                backShowInfo : {},
                visible : true
            });
        }else {
            var cRow = this.state.cRow;
            var res = cRow[0];
            var that = this;
            if(cRow.length > 0) {
                const backShowInfo = {};
                let id = this.state.cRow[0].key;
                this.getManagerInfo(id)
                        .then(ress => {
                    let res = ress.result;
                    backShowInfo.username = res.username;
                    backShowInfo.password = res.password;
                    backShowInfo.name = res.name;
                    backShowInfo.mobile = res.mobile;
                    backShowInfo.department = res.department;
                    backShowInfo.id = id;
                    backShowInfo.role = res.role.map(val => {
                        return {
                            id : val.id,
                            val : val.name
                        }
                    });
                    this.setState({
                        modalTitle : '修改账户',
                        isModify : 1,
                        backShowInfo,
                        visible : true
                    });
                });
            }
            
        }
      
    }
    //获取用户信息
    getManagerInfo = (id) => {
        return new Promise(resolve => {
            $.ajax({
                url : tools.apiUrl + 'manage/admin_info',
                type : 'post',
                data : {
                    id,
                    token : localStorage.token
                },
                success : function(res) {
                    if(res.status == 1) {
                        resolve(res);
                    }
                }
            })
        })
    }

    addCount = () => {

    }
    
    handlePage  = (page, pageSize) => {
        this.getTabsContent(page).then(tabcontent => {
            this.setState({
                cTabContent : tabcontent,
            });
        });
    }

    tabDataFormat = (data) => {
        return data.map(val => {
            let roles = [];
            if(val.role.length > 0) {
                roles = val.role.map(val => {
                    return val.name
                })
            }
            return {
                key : val.id,
                count : val.username,
                role : roles.join(','),
                name : val.name,
                phone : val.mobile,
                status : (val.status == 1 ? '启用' : '禁用'),
                cName : '',
                cTime : new Date(val.created_at * 1000).toLocaleString(),
                department : val.department
            }
        });
    }
    //获取表格内容
    getTabsContent = (page = 1) => {
        var that = this;
        return new Promise(resolve => {
            $.ajax({
                url : tools.apiUrl + 'manage/administrators_list',
                type : 'post',
                data : {
                    token : localStorage.getItem('token'),
                    page,
                },
                success : function(res) {
                    if(res.status == 1) {
                        let cTabContent = that.tabDataFormat(res.result.data);
                        resolve(cTabContent);
                        that.setState({
                            paginationC : {
                                pageSize : res.result.per_page,
                                current : res.result.current_page,
                                total : res.result.total,
                                onChange : that.handlePage
                            }
                        })
                    }
                }
            })
        })
    }
    //获取全部可选择角色
    getRoles = () => {
        return new Promise(resolve => {
            $.ajax({
                url : tools.apiUrl + 'manage/all_role',
                type : 'post',
                data : {
                    token : localStorage.token,
                },
                success : function(res) {
                    console.log(res)
                    if(res.status == 1) {
                        resolve(res.result)
                    }
                }
            })
        })
    }

    //初次渲染数据
    componentWillMount = () => {
        var that = this;
        var content = this.getTabsContent();
        var roles = this.getRoles();
        Promise.all([content, roles]).then(res => {
            var searchKeys = this.state.searchKeys;
            searchKeys[1].options = res[1].map(val => {
                return  {
                    val : val.id,
                    text : val.name
                }
            })
            this.setState({
                cTabContent : res[0],
                cRoles : res[1],
                searchKeys : searchKeys
            })
        });
    }

    //停用账户
    inactiveCount = () => {
        var cRow = this.state.cRow;
        var res = cRow[0];
        var that = this;
        if(cRow.length > 0 && res.status == '启用') {
            $.ajax({
                url : tools.apiUrl + 'manage/statusadmin',
                type : 'post',
                data : {
                    id : res.key,
                    status : -1,
                    token : localStorage.token
                },
                success : function(res) {
                    if(res.status == 1) {
                        that.handlePage();
                        that.setState({
                            cRowKey : []
                        })
                    }else {
                        message.error(res.msg);
                    }
                }
            })
        }else {
            message.error('无可操作账户');
        }
    }

    //启用账户
    activeCount = () => {
        var cRow = this.state.cRow;
        var res = cRow[0];
        var that = this;
        if(cRow.length > 0 && res.status == '禁用') {
            $.ajax({
                url : tools.apiUrl + 'manage/statusadmin',
                type : 'post',
                data : {
                    id : res.key,
                    status : 1,
                    token : localStorage.token
                },
                success : function(res) {
                    if(res.status == 1) {
                        that.handlePage();
                        that.setState({
                            cRowKey : []
                        })
                    }else {
                        message.error(res.msg);
                    }
                }
            })
        }else {
            message.error('无可操作账户');
        }
    }
    //删除
    removeCount = () => {
        var cRow = this.state.cRow;
        var res = cRow[0];
        var that = this;
        if(cRow.length > 0) {
            $.ajax({
                url : tools.apiUrl + 'manage/statusadmin',
                type : 'post',
                data : {
                    id : res.key,
                    status : 1,
                    token : localStorage.token
                },
                success : function(res) {
                    if(res.status == 1) {
                        that.handlePage();
                        that.setState({
                            cRowKey : []
                        })
                    }else {
                        message.error(res.msg);
                    }
                }
            })
        }else {
            message.error('无可操作账户');
        }
    }

    handleSearchCb = (val) => {
        console.log('cb!!!', val);
        this.doSearch(val);
    }
    doSearch = (data) => {
        var that = this;
        data.token = localStorage.token;
        if(data.time && data.time.length > 0) {
            data.created_start_time = data.time[0]._d.toLocaleDateString();
            data.created_end_time = data.time[1]._d.toLocaleDateString();
            data.time = '';
        }
        $.ajax({
            url : tools.apiUrl + 'manage/administrators_list',
            data,
            type : 'post',
            success : function(res) {
                if(res.status == 1) {
                    let cTabContent = that.tabDataFormat(res.result.data);
                    that.setState({
                        paginationC : {
                            pageSize : res.result.per_page,
                            current : res.result.current_page,
                            total : res.result.total,
                            onChange : that.handlePage,
                        },
                        cTabContent
                    })
                }else {
                    that.setState({
                        cTabContent : []
                    })
                }
                
            }
        })
    }
    render() {
        var oldData = {}; 
        //判断是否有选择
        {this.state.isModify == 1 ? oldData=this.state.backShowInfo : { }};
        //模态框控制
        const modalStyle = {
            title : this.state.modalTitle,
            className : 'normal-modal-control',
            visible : this.state.visible,
        }
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    cRow : selectedRows,
                    cRowKey : selectedRowKeys
                })
            },
            type: 'radio',//单选,
            selectedRowKeys : this.state.cRowKey,
        };
        console.log('cTabContent', this.state.cTabContent)
        console.log('xixi???', this.props.xixi)
        return (
            <div>
                <div className="search-top">
                    <WrappedSearchForm 
                        onSearchCb={this.handleSearchCb}
                        searchKeys={this.state.searchKeys}
                    />
                </div>
                <div className="search-content">
                    <div className="city-biaotou">
                        <div className="city-biaotou-left">
                            <Button key="btn2" onClick={this.showModal} id="add_count">添加账号</Button> 
                            <Button key="btn3" onClick={this.showModal} id="modify_count">修改</Button>
                            <Button key="btn4" onClick={this.inactiveCount} >停用</Button> 
                            <Button key="btn5" onClick={this.activeCount}>启用</Button>
                            {/* <Button key="btn6" onClick={this.removeCount}>删除</Button> */}
                        </div>
                    </div>
                    <div className="search-result-box">
                        <Table 
                            rowSelection={rowSelection}
                            columns={columns}
                            dataSource={this.state.cTabContent}
                            pagination={this.state.paginationC}
                        />
                    </div>
                </div>

                {/* <Modal
                title={this.state.modalTitle}
                visible={this.state.visible}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                className='normal-modal-control'
                >
                </Modal> */}
                {/*  */}
                <WrapAddAcountForm 
                    onTableUpdate={this.handlePage} 
                    onCancel={this.handleCancel} 
                    modalStyle={modalStyle}
                    id='addOrUpdateRole' 
                    roles={this.state.cRoles} 
                    oldData={oldData}
                    isModify={this.state.isModify}
                />
            </div>
        )
    }
}

export default AuthorityManagementAcount